import axios from "axios"
import { getToken } from "@/utils/auth.ts"
import { ElMessage } from "element-plus"
import { useLoginStore } from "@/stores/login.ts"

const config = {
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 3000
}

const service = axios.create(config)

service.interceptors.request.use(
  (config) => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = `${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    const { code, message } = response.data
    const store = useLoginStore()
    if (code === 422) {
      store.logout()
      ElMessage.error(message)
      window.location.reload()
    }

    if (code !== 200) {
      ElMessage.error(message)
      return Promise.reject(message)
    }
    return response.data
  },
  (error) => {
    const { status, data } = error.response ?? {}
    const message = data?.message || "请求失败"

    if (status === 500) {
      ElMessage.error(message)
    }
    return Promise.reject(error)
  }
)

export default service
